#!/bin/bash
# 作用：DWS层（历史至今汇总），每日数据装载（DWD -> DWS_td）

# 1.判断参数
if [ $# -lt 1 ]
then
	echo "请输入正确参数表名/all" && exit
fi

# 2.定时时间属性
[ "$2" ] && dateStr=$2 || dateStr=`date -d '-1 day' +%F`

# 3.执行导数SQL
dws_trade_user_order_td="insert overwrite table dws_trade_user_order_td partition (dt='${dateStr}')
select user_id,
       min(order_date_first),
       max(order_date_last),
       sum(order_count_td),
       sum(order_num_td),
       sum(original_amount_td),
       sum(activity_reduce_amount_td),
       sum(coupon_reduce_amount_td),
       sum(total_amount_td)
from (
         (
             select user_id,
                    order_date_first,
                    order_date_last,
                    order_count_td,
                    order_num_td,
                    original_amount_td,
                    activity_reduce_amount_td,
                    coupon_reduce_amount_td,
                    total_amount_td
             from dws_trade_user_order_td
             where dt = date_sub('${dateStr}', 1)
         )
         union all
         (select user_id,
                 min(dt),
                 max(dt),
                 sum(order_count_1d),
                 sum(order_num_1d),
                 sum(order_original_amount_1d),
                 sum(activity_reduce_amount_1d),
                 sum(coupon_reduce_amount_1d),
                 sum(order_total_amount_1d)
          from dws_trade_user_order_1d
          where dt = '${dateStr}'
          group by user_id)
     ) t1
group by user_id;"
dws_user_user_login_td="insert overwrite table dws_user_user_login_td partition (dt='${dateStr}')
select user_id,
       max(login_date_last),
       sum(login_count_td)
from (
         (select user_id, login_date_last, login_count_td
          from dws_user_user_login_td
          where dt = date_sub('${dateStr}', 1)
         )
         union all
         (
             select user_id,
                    max(date_id) last_login,
                    count(1)     login_count
             from dwd_user_login_inc
             where dt = '${dateStr}'
             group by user_id
         )
     ) t1
group by user_id;"

case $1 in
"all")
	$HIVE_HOME/bin/hive -e "${dws_trade_user_order_td}${dws_user_user_login_td}"
;;
"dws_trade_user_order_td")
    $HIVE_HOME/bin/hive -e "${dws_trade_user_order_td}"
;;
"dws_user_user_login_td")
    $HIVE_HOME/bin/hive -e "${dws_user_user_login_td}"
;;
esac
